package com.wendy.common.web.Interceptor;

import com.wendy.common.core.api.PageInterceptorApi;
import com.wendy.common.core.page.PageBO;
import com.wendy.common.core.page.PageDomain;
import com.wendy.common.core.utils.StringUtils;
import com.wendy.utils.web.page.TableSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The type Page interceptor.
 * 主要是拦截controller层方法，如果拦截的方法以/page结尾 ，则自动把分页参数放入线程变量中
 *
 * @author wendy
 * @date 2020 /12/2 16:08
 */
public class PageInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(HandlerInterceptor.class);
    @Resource
   private  PageInterceptorApi pageInterceptorApi;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();
        if (StringUtils.upperCase(methodName).endsWith("PAGE")) {
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
           // String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageBO bo =new PageBO(reasonable,pageNum,pageSize,pageDomain.getOrderByColumn(),pageDomain.getIsAsc());
            pageInterceptorApi.startPage(bo);
            log.debug("分页拦截器拦截preHandle");
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(pageInterceptorApi.removePage()){
            log.debug("分页拦截器拦截removePage");
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    public PageInterceptorApi getPageInterceptorApi() {
        return pageInterceptorApi;
    }

    public void setPageInterceptorApi(PageInterceptorApi pageInterceptorApi) {
        this.pageInterceptorApi = pageInterceptorApi;
    }
}
